package com.usermanage.util;

import com.aliyun.oss.OSSClient;
import com.usermanage.ExceptionConfig.MyException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by 過客 on 2018/3/20
 */
@Slf4j
public class OssUtil {
    //    static Logger logger = Logger.getLogger(HelloOSS.class);

    // endpoint是访问OSS的域名。如果您已经在OSS的控制台上 创建了Bucket，请在控制台上查看域名。
    // 如果您还没有创建Bucket，endpoint选择请参看文档中心的“开发人员指南 > 基本概念 > 访问域名”，
    // 链接地址是：https://help.aliyun.com/document_detail/oss/user_guide/oss_concept/endpoint.html?spm=5176.docoss/user_guide/endpoint_region
    // endpoint的格式形如“http://oss-cn-hangzhou.aliyuncs.com/”，注意http://后不带bucket名称，
    // 比如“http://bucket-name.oss-cn-hangzhou.aliyuncs.com”，是错误的endpoint，请去掉其中的“bucket-name”。
    public static final String endpoint = "http://oss-cn-shanghai.aliyuncs.com";

    // accessKeyId和accessKeySecret是OSS的访问密钥，您可以在控制台上创建和查看，
    // 创建和查看访问密钥的链接地址是：https://ak-console.aliyun.com/#/。
    // 注意：accessKeyId和accessKeySecret前后都没有空格，从控制台复制时请检查并去除多余的空格。
    public static final String accessKeyId = "LTAIQ1Das04L34w3";
    public static final String accessKeySecret = "S9w4AF8Jh03uQ1mY9HAIWsXCk0Bd1z";

    // Bucket用来管理所存储Object的存储空间，详细描述请参看“开发人员指南 > 基本概念 > OSS基本概念介绍”。
    // Bucket命名规范如下：只能包括小写字母，数字和短横线（-），必须以小写字母或者数字开头，长度必须在3-63字节之间。
    public static final String bucketName = "pinzafile";

    // Object是OSS存储数据的基本单元，称为OSS的对象，也被称为OSS的文件。详细描述请参看“开发人员指南 > 基本概念 > OSS基本概念介绍”。
    // Object命名规范如下：使用UTF-8编码，长度必须在1-1023字节之间，不能以“/”或者“\”字符开头。
    public static final String firstKey = "pinzafile";

//    http://pinzafile.oss-cn-shanghai.aliyuncs.com/EOS/pic/20181005132237183/111.png
    public static final String ossUrl = "EOS/pic/";  //management测试url
//    public static final String ossUrl = "management/picture/";  //management正式url

    public static OSSClient getOSSClientInstance(){
        return new OSSClient(endpoint, accessKeyId, accessKeySecret);
    }

    public static Boolean deletePic(String url){
        log.info("进入OSS删除方法");
        Boolean bool = false;
        OSSClient ossClient =null;
        try {
            ossClient = OssUtil.getOSSClientInstance();
            if (ossClient.doesObjectExist(bucketName,url)) {
                ossClient.deleteObject(bucketName, url);
                bool = true;
            }
        }catch (Exception e){
            log.error("OSS数据异常");
            if (ossClient!=null){
                ossClient.shutdown();
            }
            throw new MyException("OSS删除异常");

        }finally {
            if (ossClient!=null){
                ossClient.shutdown();
            }
        }
        return bool;
    }

    public static String uploadByte(byte[] content) throws IOException {
        String url = null;
        String filepath = StringUtil.getTimeString();
        OSSClient ossClient = OssUtil.getOSSClientInstance();
        if (ossClient.doesBucketExist(bucketName)) {
            System.out.println("您已经创建Bucket：" + bucketName + "。");
            url = ossUrl + filepath + "/pic.jpg";
            ossClient.putObject(bucketName, url, new ByteArrayInputStream(content));
        } else {
            System.out.println("您的Bucket不存在，创建Bucket：" + bucketName + "。");
            ossClient.createBucket(OssUtil.bucketName);
            url = ossUrl + filepath + "/pic";
            ossClient.putObject(bucketName, url, new ByteArrayInputStream(content));
        }
        // 关闭client
        ossClient.shutdown();
        if (StringUtils.isNotBlank(url)) {
//            return "http://pinzafile.oss-cn-shanghai.aliyuncs.com/" + url;
            return url;
        } else {
            return null;
        }
    }



    public static String upload(MultipartFile pic) throws IOException {
        if (StringUtils.isNotBlank(pic.getOriginalFilename())){
            String url = null;
            String filepath = StringUtil.getTimeString();
            OSSClient ossClient = OssUtil.getOSSClientInstance();
            if (ossClient.doesBucketExist(bucketName)) {
                System.out.println("您已经创建Bucket：" + bucketName + "。");
                url = ossUrl+filepath+"/"+pic.getOriginalFilename();
                ossClient.putObject(bucketName, url, pic.getInputStream());
            } else {
                System.out.println("您的Bucket不存在，创建Bucket：" + bucketName + "。");
                // 创建Bucket。详细请参看“SDK手册 > Java-SDK > 管理Bucket”。 http://pinzafile.oss-cn-shanghai.aliyuncs.com/pictest/qqq.jpg
                // 链接地址是：https://help.aliyun.com/document_detail/oss/sdk/java-sdk/manage_bucket.html?spm=5176.docoss/sdk/java-sdk/init
                ossClient.createBucket(OssUtil.bucketName);
                // 上传文件流
//        InputStream inputStream = new FileInputStream("localFile");
                url = ossUrl+filepath+"/"+pic.getOriginalFilename();
                ossClient.putObject(bucketName, url, pic.getInputStream());
            }
// 关闭client
            ossClient.shutdown();
            if (StringUtils.isNotBlank(url)){
                return url;
//                return " http://pinzafile.oss-cn-shanghai.aliyuncs.com/"+url;
            }else{
                return null;
            }
        }else{
            return null;
        }
    }

    public static List<String> uploadPics(MultipartFile[] file) throws IOException {
        List<String> list = new ArrayList<>();
        try {
            for (MultipartFile pic : file) {
                String url = upload(pic);
                if (StringUtils.isNotBlank(url)){
                    list.add(url);
                }
            }
        }catch (Exception e){
            for (String url : list) {
                OssUtil.deletePic(url);
            }
            throw new MyException("OSS文件上传异常");
        }
        return list;
    }

//    public static boolean checkPic(String url) throws IOException {
//
//    }

}
